var express = require('express');
var router = express.Router();
// 登录注册逻辑

// 引入db
const myquery = require('../tools/db');

// 注册逻辑
/* 
* 参数必传： username   password   pass2
*/
router.post('/register',async (req,res,next)=>{
  // 接参 
  let {username,password,pass2} = req.body;
  // 判断是否为空
  if(!username || !password || !pass2){
    next('用户名或密码不能为空');
    return;
  }

  // 判断两次密码是否一致
  if(password != pass2){
    next('两次密码不一致');
    return;
  }

  // 判断用户名是否存在
  let sql = `select * from member where username='${username}'`;
  let [err,result] = await myquery(sql);

  // 判断是否有sql语句错误
  if(err){
    next(err);
    return;
  }

  if(result.length > 0){
    next('用户名已存在');
    return;
  }

  // 不存在在表中添加记录
  let sql1 = `insert into member (username,password) values ('${username}','${password}')`;

  let [err1,result1] = await myquery(sql1);
  if(err1){
    next(err1);
    return;
  }

  if(result1.insertId > 0){
    res.send({code:200,msg:'注册成功'})
  }else{
    next('请稍后再试')
  }

})


// 登录逻辑  username  password
router.post('/login',async (req,res,next)=>{
   // 接参 
   let {username,password} = req.body;
   // 判断是否为空
   if(!username || !password){
     next('用户名或密码不能为空');
     return;
   }
   // 判断用户名和密码是否一样
   let sql = `select * from member where username='${username}' and password = '${password}'`;
   let [err,result] = await myquery(sql);
 
   // 判断是否有sql语句错误
   if(err){
     next(err);
     return;
   }

   if(result.length > 0){
     res.send({code:200,msg:'登录成功'})
   }else{
    next('用户名或密码错误')
   }
 


})


module.exports = router;
